X

Node.js

Authenticate a user with Express Sessions

November 3, 2022

/*

Save the Session when a user Logs in


*/

Let's start with the login route. When a user submits a form with their username & password, it will take them to this route. Their credentials will be checked to see if they're correct. If they are, will save a session back to the mongodb store by making a username property on the session object with the username in it. Will then redirect the user to the admin page. If the credentials are not true then will redirect them to the index page.

Saving a session to mongodb store

/*

Authenticating Routes


*/

We just got sent to the admin route. We'll check the req.session.username property that we set if the username & password was true. If the property has the username in it then will render the admin page. If it doesn't we'll redirect them back to index. We'll do the same thing for any other routes that will be authenticated with sessions.

Authenticate sessions on routes

/*

Destroying the Session when user logs out


*/

Lastly, we have our logout route. Their will be a link displayed on the pages that used authentication. We want to destroy the session in the store when we click the link. We can do this by using the req.session.destroy method. This method takes 1 argument,

A callback function with an error object as it's parameter.

Destroy a session in the store


About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.